<style lang="less">
.title-text span {
  display: block; /*设置为块级元素会独占一行形成上下居中的效果*/
  position: relative; /*定位横线（当横线的父元素）*/

  color: black; /*居中文字的颜色*/
  font-weight: bold;
  text-align: center;
}

.title-text span:before,
.title-text span:after {
  content: "";
  position: absolute; /*定位背景横线的位置*/
  top: 50%;
  background: #dfdfdf; /*背景横线颜色*/
  width: 44%; /*单侧横线的长度*/
  height: 1px;
}

.title-text span:before {
  left: 0; /*调整背景横线的左右距离*/
}

.title-text span:after {
  right: 0;
}
// .ivu-select-dropdown-list {
//   height: 200px;
//   overflow-y: auto;
// }
.btns{
        background-color: white;
        padding: 20px 0 0 0;
    }
.channelClick{
        padding-bottom: 16px;
        display: flex;
        flex-flow: row;
        justify-content: flex-end;
        align-items: center;
    }
</style>
<template >

  <div class="search" style="background-color: rgb(255,255,255)">
    <Row  class="btns">
      <i-col class="channelClick">
        <Button @click="handleBack" :size="buttonSize" style="margin-right: 24px;" label="large" type="primary">返回</Button>
        <Button @click="handleCommit('companyForm')"  style="margin-right: 24px;" v-if="this.modalType != 3" :size="buttonSize" label="large"
          type="primary">提交</Button>
        <Button @click="handle('companyForm')" style="margin-right: 24px;" v-if="this.modalType != 3" :size="buttonSize" label="large"
          type="primary">保存</Button>
      </i-col>
    </Row>
    <div class="addInfo" style="display: block" id="thirdCompany">
      <h2 class="title-text"><span id="gkType">车辆信息</span></h2>
      <Row style="margin-top: 1%;border: 1px solid #dcdee2; border-color: #e8eaec;    margin: 8px;">
        <Form ref="companyForm" :model="companyForm" :rules="ruleValidate" :label-width="140">
          <Row style="padding-top: 11px">
            <i-col span="8">
              <FormItem label="申请时间" prop="createTime" style="width: 30%">
                <Input type="text" size="default" disabled v-model="companyForm.createTime" clearable
                  style="width: 200px" />
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="合作商名称" prop="channelId" style="width: 30%">
                <Select v-model="companyForm.channelId" v-bind:disabled="companyForm.idCard" filterable :label-in-value="true" @on-change="selectPord"
                  style="    width: 200px;" size="default">
                  <Option v-for="item in baseInfo" :value="item.id" :key="item.id">{{ item.channelFullName }}</Option>
                </Select>
              </FormItem>
            </i-col>

            <i-col span="8">
              <Form-item label="是否已上牌" prop="useCarNumber">
                <RadioGroup v-model="companyForm.useCarNumber"  @on-change="checkLimitPut()">
                    <Radio v-bind:disabled="companyForm.disabled" label="1" >是</Radio>
                    <Radio v-bind:disabled="companyForm.disabled" label="0">否</Radio>
                </RadioGroup>
              </Form-item>
            </i-col>
            
          </Row>
          <Row>
            <i-col span="8">
              <Form-item label="车辆类型" prop="carType">
                <Select v-model="companyForm.carType" v-bind:disabled="companyForm.disabled" placeholder="请选择" clearable
                  style="width: 200px" size="default">
                  <Option value="01">乘用车</Option>
                  <Option value="02">商用车</Option>
                </Select>
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="品牌" prop="brand">
               <div @click="queryVehicleData" style="width: 200px">
                <Input type="text" size="default" disabled v-model="companyForm.brand" clearable style="width: 200px" icon="ios-search" />
               </div>
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="车型" prop="model" size="default">
              <div @click="queryVehicleData" style="width: 200px">
                <Input type="text" size="default" disabled v-model="companyForm.model" clearable style="width: 200px" icon="ios-search" />
               </div>
              </Form-item>
            </i-col>
          </Row>

          <Row>
            <i-col span="8">
              <Form-item label="款式" prop="style">
                <div @click="queryVehicleData" >
                <Input type="text" size="default" disabled v-model="companyForm.style" clearable placeholder="点击查询自动代入"
                 style="width: calc(100% + 340px)" icon="ios-search" />
                </div>
              </Form-item>
            </i-col>
            <i-col span="8">
            <Form-item>
                
            </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="VIN号" prop="vin">
                <Input type="text" v-bind:disabled="companyForm.idCard" size="default" v-model="companyForm.vin"
                  clearable style="width: 200px" />
              </Form-item>
            </i-col>
          </Row>

          <Row>
            <i-col span="8">
              <Form-item label="表显里程" prop="apparentMileage">
                <Input type="number" v-bind:disabled="companyForm.disabled" size="default"
                  v-model="companyForm.apparentMileage" style="width: 200px" >
                  <span slot="append">/KM</span>
                </Input>
              </Form-item>
            </i-col>

            <i-col span="8">
              <Form-item label="开票日期" prop="invoiceTime">
                <Date-picker v-bind:disabled="companyForm.disabled" type="date" size="default" :options="options3"
                 :value="companyForm.invoiceTime" @on-change="companyForm.invoiceTime=$event" placeholder="选择日期" style="width: 200px"></Date-picker>
              </Form-item>
            </i-col>

            <i-col span="8">
              <Form-item label="车辆出厂日期" prop="manufactureDate">
                <Date-picker v-bind:disabled="companyForm.disabled" type="date" size="default" :options="options3"
                 :value="companyForm.manufactureDate" @on-change="companyForm.manufactureDate=$event" placeholder="选择日期" style="width: 200px"></Date-picker>
              </Form-item>
            </i-col>
          </Row>

          <Row>
            <i-col span="8">
              <Form-item label="所有人" prop="ownerName">
                <Input type="text" v-bind:disabled="companyForm.disabled" size="default" v-model="companyForm.ownerName"
                  clearable placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="所有人号码" prop="ownerCardId">
                <Input type="text" v-bind:disabled="companyForm.disabled" size="default" maxlength="20"
                  v-model="companyForm.ownerCardId" clearable placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="原使用性质" prop="useCharacter">
                <Select v-model="companyForm.useCharacter" v-bind:disabled="companyForm.disabled" placeholder="请选择"
                  clearable style="width: 200px" size="default">
                  <Option value="01">运营</Option>
                  <Option value="02">非运营</Option>
                </Select>
              </Form-item>
            </i-col>
          </Row>

          <Row>
            <i-col span="8">
              <Form-item label="指导价" prop="guidancePrice">
                <Input type="text" size="default" disabled v-model="companyForm.guidancePrice" clearable maxlength="20"
                  placeholder="请输入" style="width: 200px" >
                  <span slot="append">￥</span>
                </Input>
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="排量" prop="outputVolume">
                <Input type="number" v-bind:disabled="companyForm.disabled" size="default" v-model="companyForm.outputVolume"  placeholder="请输入" style="width: 200px" >
                <span slot="append">T/L</span>
                </Input>
                
              </Form-item>
            </i-col>

            <i-col span="8">
              <div v-for="(item,index) in companyForm.addressinfo" :key="index">
                <FormItem label="上牌省市" :prop="'addressinfo['+index+'].detailAddress'"
                  :style="{'z-index':'99'-index,'position':'relative'}" :rules="Number(companyForm.useCarNumber)?limitPut3:notLimitPut3">

                  <Cascader :load-data="loadData" v-bind:disabled="companyForm.disabled" :data="location" 
                    style="width:200px;height: 33px;" size="default" v-model="item.detailAddress" placeholder="下拉选择省市"
                    class="show_cascader_input" :clearable="true" >
                  </Cascader>

                </FormItem>
              </div>
            </i-col>

          </Row>

          <Row>
            <i-col span="8">
              <Form-item label="发动机号" prop="engineNumber">
                <Input type="text" v-bind:disabled="companyForm.disabled" size="default"
                  v-model="companyForm.engineNumber" clearable placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="车身颜色" prop="bodyColor">
                <Input type="text" v-bind:disabled="companyForm.disabled" size="default" v-model="companyForm.bodyColor"
                  clearable placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="总过户次数" prop="transferNumber">
                <Input type="number" v-bind:disabled="companyForm.disabled" size="default"
                  v-model="companyForm.transferNumber"  placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>
          </Row>

          <Row>
            <i-col span="8">
              <Form-item label="燃料类型" prop="fuelType">
                <Select v-bind:disabled="companyForm.disabled" v-model="companyForm.fuelType" placeholder="请选择"
                  clearable style="    width: 200px;" size="default">
                  <Option value="01">燃油</Option>
                  <Option value="02">新能源</Option>
                </Select>
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="车牌号" prop="carNumber" :rules="Number(companyForm.useCarNumber)?limitPut:notLimitPut">
                <Input v-bind:disabled="companyForm.disabled" type="text" size="default" v-model="companyForm.carNumber" 
                  clearable placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>

            <i-col span="8">
              <Form-item label="首次登记日期" prop="firstLicensePlateDate" :rules="Number(companyForm.useCarNumber)?limitPut2:notLimitPut2">
                <Date-picker v-bind:disabled="companyForm.disabled" type="date" size="default" :options="options3"
                  :value="companyForm.firstLicensePlateDate" @on-change="companyForm.firstLicensePlateDate=$event" placeholder="选择日期" style="width: 200px"></Date-picker>
              </Form-item>
            </i-col>
            
          </Row>

          <Row >
            <i-col span="8">
              <Form-item label="车辆评估价" prop="evaluationPrice">
                <Input size="default" v-bind:disabled="companyForm.disabled" v-model="companyForm.evaluationPrice" placeholder="请输入" style="width: 200px" >
                <span slot="append">￥</span>
                </Input>
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item label="有效期天数" prop="validityDays">
                <Input size="default" v-bind:disabled="companyForm.disabled" v-model="companyForm.validityDays" placeholder="请输入" style="width: 200px" />
              </Form-item>
            </i-col>
            <i-col span="8">
              <Form-item>
                <Button @click="openFileUpload('companyForm')" size="default"
                  style=" color: #2b85e4;   background-color:white;border: none">附件{{annexName}}</Button>
              </Form-item>
            </i-col>
          </Row>

        </Form>
      </Row>
    </div>
     <!--品牌车型弹窗-->
    <div v-if="isShowModel">
            <char-cascade   @close-model="closeModel" @carinfo="carinfo"></char-cascade>
      </div>
    <div v-if="isShowFile" >
            <!--附件-->
            <file-operation  :uploadParam="uploadParam" :isInt="canUpload" :path="path"  ></file-operation>
        </div>

    <div v-if="seeShowFile">
       <file-operation :uploadParam="uploadParam" :isInt="canUpload" :path="path" readOnly ></file-operation>
    </div>
  </div>

</template>

<script>
import PlaceCascade from "@/components/place-cascade";
import { province, city, area } from "_p/afs-apply/assets/js/staticData.js";
import { getLocation,getBaseInfoByType,getFilterParams } from "@/projects/afs-channel/api/common/common";
import CharCascade from "@/components/char-cascade";
import circleLoading from "_c/circle-loading/circle-loading.vue";
import {getRoleType,getBaseInfoByRole} from "_p/afs-channel/api/common/common.js";
import FileOperation from "_p/basic/pages/image/upload-file/fileOperation.vue";
import {checkFile} from "_p/basic/api/image/image-upload";

import {
  getChannelListingCarTemp,
  save,
  deleteChannel,
  getListData,
  edit,
  getModelList,
  getById
} from "@/projects/afs-apply/api/register-mng/listRecord";
import * as utils from "@/projects/afs-apply/assets/js/utils";
import timeUtils from "@/libs/util.js";
export default {
  name: "list-add-edit",
  components: {
    CharCascade,FileOperation
  },
  data() {
    const validatePassword = (rule, value, callback) => {
      if (value.length != 18) {
        callback(new Error("请输入正确的身份证"));
      } else {
        callback();
      }
    };
    const validateVin = (rule, value, callback) => {
      value=value.replace(/\s*/g,"");
      if (value.length != 17) {
        callback(new Error("请输入正确的VIN码"));
      } else {
        // 先判断只能有字母和数字
        var  dd =/^[0-9a-zA-Z]+$/;
        if(!dd.test(value)){
           callback(new Error("只能有英文和数字"));
        }else{
          var  vv = /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/;
          if(!vv.test(value)){
             callback(new Error("必须有英文和数字"));
          } 
        }
        callback();
      }
    };

    
    const validateEngine = (rule, value, callback) => {
      value=value.replace(/\s*/g,"");
     
        // 先判断只能有字母和数字
        var  dd =/^[0-9a-zA-Z]+$/;
        if(!dd.test(value)){
           callback(new Error("只能有英文和数字"));
        }else{
          var  vv = /^(\d+[a-zA-Z]+|[a-zA-Z]+\d+)([0-9a-zA-Z]*)$/;
          if(!vv.test(value)){
             callback(new Error("必须有英文和数字"));
          } 
        }
        callback();
      
    };
    // 只能有英文和数字
    const validateCode = (rule, value, callback) => {
      value=value.replace(/\s*/g,"");
        // 先判断只能有字母和数字
        var  dd =/^[0-9a-zA-Z]+$/;
        if(!dd.test(value)){
           callback(new Error("只能有英文和数字"));
        }
        callback();
     
    };
    const validateMobile = (rule, value, callback) => {
      var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
      if (!reg.test(value)) {
        callback(new Error("手机号格式错误"));
      } else {
        callback();
      }
    };

    const val = (rule, value, callback) => {
      if (value<=0) {
        callback(new Error("必须大于0"));
      } else {
        if(!utils.isPositiveInteger(value)){
           callback(new Error("只能是整数!"));
          
        }else{
            callback();
        }
        
      }
    };

    const output = (rule, value, callback) => {
      if (value<=0) {
        callback(new Error("必须大于0"));
      } else {
        if(!utils.isThreeDicmal(value)){
           callback(new Error("最多三位小数!"));
        }else{
            callback();
        }
        
      }
    };

    const price = (rule, value, callback) => {
      if (value<=0) {
        callback(new Error("必须大于0"));
      } else {
        if(!utils.isTwoDicmal(value)){
           callback(new Error("评估价最多2位小数!"));
          
        }else{
            callback();
        }
        
      }
    };

    let plateNoValiate=(rule, value, callback)=>{
                if (value) {
                    if(!utils.isPlateNo(value)) {
                        callback(new Error("至少5位字母,中文,数字"))
                        return;
                    }else{
                        let firstchar=value.substr(0,1);
                        let secondechar=value.substr(1,1);
                        // console.log(/[\u4e00-\u9fa5]/.test(firstchar),"/[\u4e00-\u9fa5]/.test(firstchar)")
                        if(!/[\u4e00-\u9fa5]/.test(firstchar)||!/[A-Za-z]/.test(secondechar)){
                            callback(new Error("车牌号首位为中文,第二位为英文"))
                            return;
                        }
                    }
                }
                callback()
            }

    return {
      
      // 附件上传的数据
      isShowFile:false,
      seeShowFile:false,
      canUpload:false,
      annexName:"",
      uploadParam: {
                busiNo: "",
                belongNo: "carRecordApply",
                busiType: "carRecordApply",
                busiData: {
                  useCarNumber: "1"
                }
            },
      path:"channel",
      filrData: {
        useCarNumber: "1"
        },
      options3: {
                    disabledDate (date) {
                        return date && date.valueOf() >= Date.now() - 86400000+(3600 * 1000 * 24);
                    }
                },
      buttonSize: "large",
      // 下面用于车型库
      isShowModel: false,

      // 引用别人的省市
      location: [],
      totalLevel: 2,

      loading: true,
      dpLoading: false, // 部门树加载
      operationLoading: false,
      importLoading: false,
      loadingExport: true,

      modalType: 0,
      companyForm: {
        disabled: null, // 控制隐藏用的
        idCard: null, // 单独控制身份证不可以修改

        createTime: null, // 申请时间
        channelId: "", // 合作商名称
        carType: null, // 车辆类型
        brand: null, //品牌
        model: null, // 车型
        style: null, //款式
        vin: null, // vin号
        apparentMileage: null, //表显里程
        firstLicensePlateDate: null, // 首次登记时间
        manufactureDate: null, //车辆出厂日期
        invoiceTime:null, // 开票日期
        ownerName: null, //所有人
        ownerCardId: null, // 证件号码
        useCharacter: null, //原使用性质
        guidancePrice: null, // 指导价
        outputVolume: null, //排量
        cardProvince: null, //上牌省
        cardCity: null, //上牌市
        engineNumber: null, //发动机号
        bodyColor: null, //车身颜色
        transferNumber: null, //总过户次数
        fuelType: null, //燃料类型
        carNumber: null, // 车牌号
        useCarNumber: "1", // 是否必填车牌号
        brandId:null, //品牌id
        modelId:null, // 车型id
        styleId:null, //款式id
        channelBelong:null, //渠道归属00:SP 01:直营 02:总对总
        // 省市用的
        position: "",
        // 地址信息
        addressinfo: [
          {
            detailAddress: []
          }
        ]
      },

      // 存放合作商的集合
      baseInfo: [],
      // 选中的数据集合
      channelMessage:{},
      // 下面是用于权限控制的 01:代表新车  02 代表二手车  03代表新车二手车都有
      businessType: null,
      ownBusinessType: null,

      // 下面用于表单必填验证
      ruleValidate: {
        ownerName: [
          { required: true, message: "所有人不能空", trigger: "blur" }
        ],
        ownerCardId: [
          { required: true, message: "所有人号码不正确", trigger: "blur" },
           { validator: validateCode, trigger: "blur" }
        ],
        vin: [
          { required: true, message: "请输入正确的VIN码", trigger: "blur" },
          { validator: validateVin, trigger: "blur" }
        ],
        manufactureDate: [
          {
            required: true,
            message: "车辆出厂日期不能空",
            trigger: "blur"
          }
        ],
        invoiceTime: [
          {
            required: true,
            message: "开票日期不能空",
            trigger: "blur"
          }
        ],
        guidancePrice: [
          { required: true, message: "指导价不能空", trigger: "blur" }
        ],
        outputVolume: [
          { required: true, message: "排量不能为空", trigger: "blur" },
          { validator: output, trigger: "blur" }
        ],
        engineNumber: [
          { required: true, message: "发动机号不能为空", trigger: "blur" },
          { validator: validateEngine, trigger: "blur" }
        ],
        bodyColor: [
          { required: true, message: "车身颜色不能为空", trigger: "blur" }
        ],
        fuelType: [
          { required: true, message: "燃料类型不能为空", trigger: "blur" }
        ],
        carType: [
          { required: true, message: "请选择车辆类型", trigger: "blur" }
        ],
        apparentMileage: [
          { required: true, message: "表里程不能为空", trigger: "blur" },
          { validator: val, trigger: "blur" }
        ],
        useCharacter: [
          { required: true, message: "请选择使用性质", trigger: "blur" }
        ],
        evaluationPrice: [
          { required: true, message: "请输入评估价", trigger: "blur" },
          { validator: price, trigger: "blur" }
        ],
        validityDays: [
          { required: true, message: "请输入有效期", trigger: "blur" },
          { validator: val, trigger: "blur" }
        ]  
      },
      limitPut:[
           { required: true,  message:  "请输入车牌号",  trigger: "blur" },
           { validator: plateNoValiate, trigger: "blur" }

        ],
        notLimitPut:[
         { required: false, message: "请输入车牌号", trigger: "blur" },
         { validator: plateNoValiate, trigger: "blur" }
        ],

        limitPut2:[
           { required: true, message:  "请选择首次登记日期",  trigger: "blur" },

        ],
        notLimitPut2:[
         { required: false,  message: "请选择首次登记日期", trigger: "blur" },
        ],

        limitPut3:[
           { required: true, type: 'array', message:  "请选择上牌省市",  trigger: "blur" },

        ],
        notLimitPut3:[
         { required: false, type: 'array', message: "请选择上牌省市", trigger: "blur" },
        ],
      submitLoading: false,
      total: 0
    };
  },
  methods: {
    init() {
      
      console.log(this.afs.getPageParams(this).type);
      if (this.afs.getPageParams(this).type == 1) {
        this.annexName="添加"
        this.getTime();
        this.getRole();
      } else {
        this.companyForm.id = this.afs.getPageParams(this).id;
        if (this.afs.getPageParams(this).type == 2) {
          this.annexName="编辑";
          this.modalType = 1;
        } else if (this.afs.getPageParams(this).type == 3) {
          this.annexName="查看";
          this.modalType = 3;
        }
        this.getById();
      }
      // 获取登录这的权限
      
      // this.getBaseInfoByType();
    },
    selectPord(v){
      if(this.baseInfo.length > 0){
         for (var i = 0; i < this.baseInfo.length; i++){
            if (v.value == this.baseInfo[i].id) {
              this.channelMessage =this.baseInfo[i];
              this.companyForm.channelBelong = this.baseInfo[i].channelBelong;
              break;
            }
         }
      }
    },

    // 查询自己的权限
    getRole() {
      console.log("我要过来判断权限");
      console.log(this.$store.state.user.roles.toString());
      // 判断是管理员  全都可以操作
      if (this.$store.state.user.roles.toString().indexOf("ROLE_ADMIN") != -1) {
        this.businessType = "01";
        this.ownBusinessType = "01";
        console.log("我是管理员");
      } else {
        // 说明不是管理员 那么需要判断他有哪些管理角色
        if (
          this.$store.state.user.roles
            .toString()
            .indexOf("ROLE_OTHER_MANAGE_LISTING") != -1 
        ) {
          // 说明是新车非直营管理
          this.businessType = "01";
          console.log("我是非直营新车");
        }
       
        // 再去判断直营的角色属性
        if (
          this.$store.state.user.roles
            .toString()
            .indexOf("ROLE_OWN_MANAGE_LISTING") != -1 
        ) {
          //我是直营的新车属性
          this.ownBusinessType = "01";
          console.log("我是直营新车");
        }
      }
      this.getBaseInfoByRole();
    },
    // 获取合作商信息接口
    getBaseInfoByRole() {
      let param = {
        status: "00",
        channelId: this.companyForm.channelId,
        businessType:this.businessType,
        ownBusinessType:this.ownBusinessType
      };
      getBaseInfoByRole(param).then(res => {
        this.loading = false;
        if (res.code === "0000") {
          this.baseInfo = res.data;
        }
      });
    },

    // 点击查询车型
    // 车型库弹窗出现
    queryVehicleData() {
      if(this.modalType!='3'){
        this.isShowModel = true;
        this.$emit("open-model");
      }
      
    },
    closeModel(value) {
      this.isShowModel = value;
    },
    // 根据id 去查询数据
    getById() {
      getById({ id: this.companyForm.id }).then(res => {
        this.operationLoading = false;
        if (res.code === "0000") {
          this.companyForm = res.data;
          this.companyForm.guidancePrice = this.companyForm.guidancePrice.toString();
          this.companyForm.channelId = this.companyForm.channelId.toString();
          this.companyForm.apparentMileage=this.companyForm.apparentMileage.toString();
          this.companyForm.evaluationPrice=this.companyForm.evaluationPrice.toString();
          this.companyForm.validityDays=this.companyForm.validityDays.toString();
          console.log(this.companyForm.channelId)
          console.log(this.companyForm.guidancePrice);
          this.getRole();

          // 地址信息
          this.companyForm.addressinfo = [
            {
              detailAddress: [
                this.companyForm.cardProvince,
                this.companyForm.cardCity
              ]
            }
          ];
          if (this.companyForm.status != "02") {
            this.companyForm.idCard = true;
          }
          if (this.modalType == 3) {
            this.companyForm.disabled = "disabled";
            this.companyForm.idCard = true;
          }
        }
        console.log(this.companyForm.addressinfo);
        this.uploadParam.busiNo = this.companyForm.id;
        this.uploadParam.belongNo = "carRecordApply";
        this.uploadParam.busiData.useCarNumber=this.companyForm.useCarNumber;
        this.uploadParam.busiType = "carRecordApply";
        this.canUpload=true;   
      });
    },

    // 选中款式的查询后获取的车辆信息
    carinfo(brandName, modelName, styleName, guidePrice) {
      console.log(brandName, modelName, styleName, guidePrice);
      this.companyForm.brandId=brandName.curBrandId;// 品牌id
      this.companyForm.modelId =brandName.curModelId; //车型id
      this.companyForm.styleId =brandName.curStyleId; // 款式id

      this.companyForm.brand = brandName.curBrandName; // 品牌
      this.companyForm.model = brandName.curModelName; // 车型
      this.companyForm.style = brandName.curStyleName; // 款式
      this.companyForm.guidancePrice = brandName.curGuidePrice; //指导价
    },

    // 这一块应该是有关省市区的
    getLocationData() {
      let param = "";
      param = {
        level: "1",
        upperCode: "1"
      };
      getLocation(param).then(res => {
        if (res.code == "0000") {
          res.data.value = province;
          res.data.forEach(item => {
            let obj = {
              value: item.value,
              label: item.label,
              children: [],
              level: 0,
              loading: false
            };
            this.location.push(obj);
          });
        }
      });
    },
    // 这一块应该是关系省市区的
    loadData(item, callback) {
      console.log(item);
      item.loading = true;
      let param = "";
      param = {
        level: item.level + 1,
        upperCode: item.value
      };
      getLocation({ upperCode: item.value }).then(res => {
        if (res.code == "0000") {
          res.data.forEach(val => {
            let obj = {
              value: val.value,
              label: val.label
            };
            let templevel = parseInt(item.level);
            // 当层级没有到最后一层
            console.log(templevel + 1, this.totalLevel - 1);
            if (templevel + 1 < this.totalLevel - 1) {
              obj.children = [];
              obj.level = templevel + 1;
              obj.loading = false;
            }
            item.children.push(obj);
          });
          item.loading = false;
          callback();
        }
      });
    },

    // 点击返回
    handleBack() {
      this.afs.closeTab(this);
    },

    // 点击保存
    handle(name) {
      

      this.$refs[name].validate(valid => {
        console.log(valid);
      // this.companyForm.firstLicensePlateDate = timeUtils.formatDate(this.companyForm.firstLicensePlateDate, 'YYYY-MM-DD hh:mm:ss');
      // this.companyForm.manufactureDate = timeUtils.formatDate(this.companyForm.manufactureDate, 'YYYY-MM-DD hh:mm:ss');
      this.companyForm.vin=this.companyForm.vin.replace(/\s*/g,"");
      this.companyForm.ownerName=this.companyForm.ownerName.replace(/\s*/g,"");
      this.companyForm.ownerCardId=this.companyForm.ownerCardId.replace(/\s*/g,"");
      this.companyForm.engineNumber=this.companyForm.engineNumber.replace(/\s*/g,"");
      this.companyForm.bodyColor=this.companyForm.bodyColor.replace(/\s*/g,"");
      if(this.companyForm.carNumber!=null&&this.companyForm.carNumber!=undefined&&this.companyForm.carNumber!=""){
        this.companyForm.carNumber=this.companyForm.carNumber.replace(/\s*/g,"");
      }
        if (valid) {
          if(this.companyForm.channelBelong=='01'){
        // 说明我选中是新车
        if(this.ownBusinessType==null){
          this.$Message.error("信息类型与您权限不匹配");
          return;
        }
      }else{
        if(this.businessType==null){
          this.$Message.error("信息类型与您权限不匹配");
          return;
        }
      }

      if(Number(this.companyForm.evaluationPrice)>Number(this.companyForm.guidancePrice)){
        this.$Message.error("评估价不能大于指导价");
        return;
      }

      console.log(this.companyForm.addressinfo);
      this.companyForm.cardProvince = this.companyForm.addressinfo[0].detailAddress[0];
      console.log(this.companyForm.cardProvince);
      this.companyForm.cardCity = this.companyForm.addressinfo[0].detailAddress[1];
      console.log(this.companyForm.cardCity);
      if(this.companyForm.useCarNumber=='1'){
        if(this.companyForm.firstLicensePlateDate==undefined||this.companyForm.firstLicensePlateDate==null||this.companyForm.firstLicensePlateDate==''){
          this.$Message.error("请选择首次登记日期");
          return;
        }
      }
      if(this.companyForm.manufactureDate==null||this.companyForm.manufactureDate==undefined||this.companyForm.manufactureDate==''){
        this.$Message.error("请选择车辆出厂日期");
        return;
      }
      if(this.companyForm.invoiceTime==null||this.companyForm.invoiceTime==undefined||this.companyForm.invoiceTime==''){
        this.$Message.error("请选择开票日期");
        return;
      }
      let a = Date.now();
      // 获取首次登记的时间
      var d = new Date(this.companyForm.firstLicensePlateDate);
      // 获取车辆登记日期
      var m = new Date(this.companyForm.manufactureDate);
      // 获取开票日期
      var i = new Date(this.companyForm.invoiceTime);
      console.log(d.getTime());
      console.log(d.getTime());
      if(i>m){
        this.$Message.error("开票日期不能大于出厂日期！");
        return;
      }
       if(this.companyForm.firstLicensePlateDate!=undefined && this.companyForm.firstLicensePlateDate!=null&&this.companyForm.firstLicensePlateDate!=''){
         if (a > d.getTime() + 86400000 * 183) {
        this.$Message.error("车辆首次登记日期不能大于半年！");
        return;
      }
      }
      if (a > m.getTime() + 86400000 * 366) {
        this.$Message.error("车辆出厂日期不能大于一年！");
        return;
      }
      if(a>i.getTime()+86400000 * 366){
        this.$Message.error("开票日期不能大于一年！");
        return;
      }
      if (this.companyForm.apparentMileage > 100) {
        this.$Message.error("里程不能大于100！");
        return;
      }
      // 校验正整数
      if(this.companyForm.transferNumber!=null&&this.companyForm.transferNumber!=undefined&&this.companyForm.transferNumber!=""){
        if(!utils.isPositiveInteger(this.companyForm.transferNumber)){
          this.$Message.error("过户次数只可以为正整数！");
          return;
        }
      }
          if (this.companyForm.id ==null||this.companyForm.id==undefined||this.companyForm.id=="") {
            // 只有保存
            this.companyForm.status = "02";
            //预审批信息录入
            save(this.companyForm)
              .then(res => {
                if (res.code === "0000") {
                  this.$Message.success("操作成功");
                  this.companyForm.id=res.data.id;
                  this.getById();

                  // this.companyForm.firstLicensePlateDate = this.companyForm.firstLicensePlateDate.toString();
                  // this.companyForm.manufactureDate = this.companyForm.manufactureDate.toString();
                  // 先关闭本页面再跳转页面
                  
                }
              })
              .catch(() => {});
          } else {
            // 判断进来的是不是草稿状态，不是的话变成审核状态
            if (this.companyForm.status != "02") {
              this.companyForm.status = "00";
            }
            // 修改预审批信息
            edit(this.companyForm)
              .then(res => {
                if (res.code === "0000") {
                  this.$Message.success("操作成功");
                  this.getById();
                }
              })
              .catch(() => {});
          }
        } else {
          this.$Message.error("请补全信息");
        }
      });
    },

    // 点击提交
    handleCommit(name) {
      
      
      console.log("bug")
      this.$refs[name].validate(valid => {
        console.log("进来了吗");
      this.companyForm.vin=this.companyForm.vin.replace(/\s*/g,"");
      this.companyForm.ownerName=this.companyForm.ownerName.replace(/\s*/g,"");
      this.companyForm.ownerCardId=this.companyForm.ownerCardId.replace(/\s*/g,"");
      this.companyForm.engineNumber=this.companyForm.engineNumber.replace(/\s*/g,"");
      this.companyForm.bodyColor=this.companyForm.bodyColor.replace(/\s*/g,"");
      if(this.companyForm.carNumber!=null&&this.companyForm.carNumber!=undefined&&this.companyForm.carNumber!=""){
        this.companyForm.carNumber=this.companyForm.carNumber.replace(/\s*/g,"");
      }
      // this.companyForm.firstLicensePlateDate = timeUtils.formatDate(this.companyForm.firstLicensePlateDate, 'YYYY-MM-DD hh:mm:ss');
      // this.companyForm.manufactureDate = timeUtils.formatDate(this.companyForm.manufactureDate, 'YYYY-MM-DD hh:mm:ss');
        console.log(valid);
        if (valid) {
          if(this.companyForm.channelBelong=='01'){
        // 说明我选中是新车
        if(this.ownBusinessType==null){
          this.$Message.error("信息类型与您权限不匹配");
          return;
        }
      }else{
        if(this.businessType==null){
          this.$Message.error("信息类型与您权限不匹配");
          return;
        }
      }

      if(Number(this.companyForm.evaluationPrice)>Number(this.companyForm.guidancePrice)){
        this.$Message.error("评估价不能大于指导价");
        return;
      }
      console.log("我点击了提交");
      console.log(this.companyForm.addressinfo);
      this.companyForm.cardProvince = this.companyForm.addressinfo[0].detailAddress[0];
      console.log(this.companyForm.cardProvince);
      this.companyForm.cardCity = this.companyForm.addressinfo[0].detailAddress[1];
      console.log(this.companyForm.cardCity);
      if(this.companyForm.useCarNumber=='1'){
        if(this.companyForm.firstLicensePlateDate==undefined||this.companyForm.firstLicensePlateDate==null||this.companyForm.firstLicensePlateDate==''){
          this.$Message.error("请选择首次登记日期");
          return;
        }
      }
      if(this.companyForm.manufactureDate==null||this.companyForm.manufactureDate==undefined||this.companyForm.manufactureDate==''){
        this.$Message.error("请选择车辆出厂日期");
        return;
      }
      if(this.companyForm.invoiceTime==null||this.companyForm.invoiceTime==undefined||this.companyForm.invoiceTime==''){
        this.$Message.error("请选择开票日期");
        return;
      }
      let a = Date.now();
      // 获取首次登记的时间
      var d = new Date(this.companyForm.firstLicensePlateDate);
      // 获取车辆登记日期
      var m = new Date(this.companyForm.manufactureDate);
      // 获取开票日期
      var i = new Date(this.companyForm.invoiceTime);
      console.log(d.getTime());
      if(i>m){
        this.$Message.error("开票日期不能大于出厂日期！");
        return;
      }
       if(this.companyForm.firstLicensePlateDate!=undefined && this.companyForm.firstLicensePlateDate!=null&&this.companyForm.firstLicensePlateDate!=''){
         if (a > d.getTime() + 86400000 * 183) {
        this.$Message.error("车辆首次登记日期不能大于半年！");
        return;
      }
      }
      
      if (a > m.getTime() + 86400000 * 366) {
        this.$Message.error("车辆出厂日期不能大于一年！");
        return;
      }
       if(a>i.getTime()+86400000 * 366){
        this.$Message.error("开票日期不能大于一年！");
        return;
      }
      if (this.companyForm.apparentMileage > 100) {
        this.$Message.error("里程不能大于100！");
        return;
      }
      // 校验正整数
      if(this.companyForm.transferNumber!=null&&this.companyForm.transferNumber!=undefined&&this.companyForm.transferNumber!=""){
        if(!utils.isPositiveInteger(this.companyForm.transferNumber)){
          this.$Message.error("过户次数只可以为正整数！");
          return;
        }
      }
          checkFile(this.uploadParam).then(res => {
            if (res.code === '0000') {
              if (this.companyForm.id ==null||this.companyForm.id==undefined||this.companyForm.id=="") {
            this.companyForm.status = "00";
            //预审批信息录入
            save(this.companyForm)
              .then(res => {
                if (res.code === "0000") {
                  this.$Message.success("操作成功");
                  console.log("为什么不关页面")
                  this.companyForm.id=res.data.id;
                  this.companyForm.firstLicensePlateDate = this.companyForm.firstLicensePlateDate.toString();
                  this.companyForm.manufactureDate = this.companyForm.manufactureDate.toString();
                  // 先关闭本页面再跳转页面
                  this.afs.closeTab(this);
                  // 跳转审核页面
                }
              })
              .catch(() => {});
          } else {
            this.companyForm.status = "00";
            // 修改预审批信息
            edit(this.companyForm)
              .then(res => {
                if (res.code === "0000") {
                  this.$Message.success("操作成功");
                  console.log("为什么不关页面")
                  // 先关闭本页面再跳转页面
                  this.afs.closeTab(this);
                  console.log("我要跳转");
                  // this.afs.newTab(
                  //   this,
                  //   "projects/afs-channel/pages/register-mng/list-examine/listExamine",
                  //   "挂牌车审核" + this.companyForm.ownerName,
                  //   "ios-add",
                  //   { id: this.companyForm.id },
                  //   "register-examine" + this.companyForm.id,
                  //   [],
                  //   true
                  // );
                  // 跳转审核页面
                  // this.afs.newTab(this,"projects/afs-channel/pages/register-mng/list-examine/listExamine","挂牌车审核:"+res.data.ownerName,"ios-add",{ id: this.companyForm.id },"register-examine"+id,[],true);
                }
              })
              .catch(() => {});
          }
          }else{
            this.$Message.error("请补全影像件信息！");
          }
        });
          
        } else {
          this.$Message.error("请补全信息");
        }
      });
    },
    // 上传文件页面
    openFileUpload(name) {
      if(this.companyForm.id==null||this.companyForm.id==''||this.companyForm.id==undefined){
        this.$refs[name].validate(valid => {
        console.log(valid);
      // this.companyForm.firstLicensePlateDate = timeUtils.formatDate(this.companyForm.firstLicensePlateDate, 'YYYY-MM-DD hh:mm:ss');
      // this.companyForm.manufactureDate = timeUtils.formatDate(this.companyForm.manufactureDate, 'YYYY-MM-DD hh:mm:ss');
      this.companyForm.vin=this.companyForm.vin.replace(/\s*/g,"");
      this.companyForm.ownerName=this.companyForm.ownerName.replace(/\s*/g,"");
      this.companyForm.ownerCardId=this.companyForm.ownerCardId.replace(/\s*/g,"");
      this.companyForm.engineNumber=this.companyForm.engineNumber.replace(/\s*/g,"");
      this.companyForm.bodyColor=this.companyForm.bodyColor.replace(/\s*/g,"");
      if(this.companyForm.carNumber!=null&&this.companyForm.carNumber!=undefined&&this.companyForm.carNumber!=""){
        this.companyForm.carNumber=this.companyForm.carNumber.replace(/\s*/g,"");
      }
        if (valid) {
          if(this.companyForm.channelBelong=='01'){
        // 说明我选中是新车
        if(this.ownBusinessType==null){
          this.$Message.error("信息类型与您权限不匹配");
          return;
        }
      }else{
        if(this.businessType==null){
          this.$Message.error("信息类型与您权限不匹配");
          return;
        }
      }

      if(Number(this.companyForm.evaluationPrice)>Number(this.companyForm.guidancePrice)){
        this.$Message.error("评估价不能大于指导价");
        return;
      }

      console.log(this.companyForm.addressinfo);
      this.companyForm.cardProvince = this.companyForm.addressinfo[0].detailAddress[0];
      console.log(this.companyForm.cardProvince);
      this.companyForm.cardCity = this.companyForm.addressinfo[0].detailAddress[1];
      console.log(this.companyForm.cardCity);
      if(this.companyForm.useCarNumber=='1'){
        if(this.companyForm.firstLicensePlateDate==undefined||this.companyForm.firstLicensePlateDate==null||this.companyForm.firstLicensePlateDate==''){
          this.$Message.error("请选择首次登记日期");
          return;
        }
      }
      if(this.companyForm.manufactureDate==null||this.companyForm.manufactureDate==undefined||this.companyForm.manufactureDate==''){
        this.$Message.error("请选择车辆出厂日期");
        return;
      }
      if(this.companyForm.invoiceTime==null||this.companyForm.invoiceTime==undefined||this.companyForm.invoiceTime==''){
        this.$Message.error("请选择开票日期");
        return;
      }
      let a = Date.now();
      // 获取首次登记的时间
      var d = new Date(this.companyForm.firstLicensePlateDate);
      // 获取车辆登记日期
      var m = new Date(this.companyForm.manufactureDate);
      // 获取开票日期
      var i = new Date(this.companyForm.invoiceTime);
      console.log(d.getTime());
      console.log(d.getTime());
      if(i>m){
        this.$Message.error("开票日期不能大于出厂日期！");
        return;
      }
       if(this.companyForm.firstLicensePlateDate!=undefined && this.companyForm.firstLicensePlateDate!=null&&this.companyForm.firstLicensePlateDate!=''){
         if (a > d.getTime() + 86400000 * 183) {
        this.$Message.error("车辆首次登记日期不能大于半年！");
        return;
      }
      }
      if (a > m.getTime() + 86400000 * 366) {
        this.$Message.error("车辆出厂日期不能大于一年！");
        return;
      }
      if(a>i.getTime()+86400000 * 366){
        this.$Message.error("开票日期不能大于一年！");
        return;
      }
      if (this.companyForm.apparentMileage > 100) {
        this.$Message.error("里程不能大于100！");
        return;
      }
      // 校验正整数
      if(this.companyForm.transferNumber!=null&&this.companyForm.transferNumber!=undefined&&this.companyForm.transferNumber!=""){
        if(!utils.isPositiveInteger(this.companyForm.transferNumber)){
          this.$Message.error("过户次数只可以为正整数！");
          return;
        }
      }
          if (this.companyForm.id ==null||this.companyForm.id==undefined||this.companyForm.id=="") {
            // 只有保存
            this.companyForm.status = "02";
            //预审批信息录入
            save(this.companyForm)
              .then(res => {
                if (res.code === "0000") {
                  this.$Message.success("操作成功");
                  this.companyForm.id=res.data.id;
                  // 调后台获取json
                  this.initGetFilterParams();
                  console.log(this.isShowFile);
                  if(this.modalType!='03'){
                    this.isShowFile = !this.isShowFile;
                  }else{
                    this.seeShowFile = !this.seeShowFile;
                  }
                }
              })
              .catch(() => {});
          } 
        } else {
          this.$Message.error("请补全信息");
        }
      });
          
      }else{
      // 调后台获取json
        this.initGetFilterParams();
        console.log(this.isShowFile);
        if(this.modalType!='03'){
          this.isShowFile = !this.isShowFile;
        }else{
          this.seeShowFile = !this.seeShowFile;
        }
      }
     
    },
    initGetFilterParams() {
      // let params = {
      //  id: this.companyForm.id,
      // }
      // getFilterParams(params).then(res => {
      //   if (res.code === '0000') {
            console.log(this.companyForm.id)
            this.uploadParam.busiNo = this.companyForm.id;
            this.uploadParam.belongNo = "carRecordApply";
            // this.uploadParam.busiData = res.data;
            this.uploadParam.busiType = "carRecordApply";
            this.canUpload=true;            
      //   }
      // })  
    },

    // 获取当前时间
    getTime() {
      var date = new Date();
      var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)
      var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      //修改月份格式
      if (month >= 1 && month <= 9) {
        month = "0" + month;
      }
      //修改日期格式
      if (day >= 0 && day <= 9) {
        day = "0" + day;
      }
      //修改小时格式
      if (hours >= 0 && hours <= 9) {
        hours = "0" + hours;
      }
      //修改分钟格式
      if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes;
      }
      //修改秒格式
      if (seconds >= 0 && seconds <= 9) {
        seconds = "0" + seconds;
      }
      console.log("年" + year);
      //格式(yyyy-mm-dd hh:mm:ss)
      var currentFormatDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      this.companyForm.createTime = currentFormatDate;
      console.log(currentFormatDate);
    },

    // 获取车型的接口
    getLocation() {
      let params = "";
      params = {};
      getLocation(params)
        .then(res => {
          if (res.code === "0000") {
            this.$Message.success("操作成功");
          }
        })
        .catch(() => {});
    },

    // 获取合作商信息接口
    getBaseInfoByType(v) {
      getBaseInfoByType(v).then(res => {
        this.loading = false;
        if (res.code === "0000") {
          this.baseInfo = res.data;
        }
      });
    },
    // 修改 车牌是否必输
    checkLimitPut(){
      this.uploadParam.busiData.useCarNumber=this.companyForm.useCarNumber;
      this.canUpload=true;
        if(this.companyForm.useCarNumber=="0"){
          console.log("22222")
                    this.$refs.companyForm.fields.forEach(function (e) {
                        if (e.prop == 'limitPut' && (limitPut==""||limitPut==null||limitPut==undefined)) {
                            e.validateMessage="";
                            e.validateState="";
                        }
                    })
                };
    },
  },
  // 初始化加载
  mounted() {
    this.init();
    this.getLocationData();
  }
};
</script>
